/**
 * Created by Alice on 2016/9/12 0012
 */
var temp = new Date();
var defaultStartTime = temp.getFullYear() + "-01-01";
var resultValue = [];
$(function () {
    //查询的开始时间默认给今天
    $('#startTime').datetimepicker({
        bootcssVer: 3,
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        weekStart: "1",
        format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
        language: 'zh-CN', //汉化
        autoclose: true //选择日期后自动关闭
    }).on('changeDate', function (ev) {
        console.log(ev.date.valueOf());
    });
    $('#endTime').datetimepicker({
        bootcssVer: 3,
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        weekStart: "1",
        format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
        language: 'zh-CN', //汉化
        autoclose: true //选择日期后自动关闭
    }).on('changeDate', function (ev) {
        console.log(ev.date.valueOf());
    });
    $("#endTime").find("input").val(utils.get_date(0));
    $("#startTime").find("input").val(defaultStartTime);
    init();
    $(".container-fluid").show();
    $("#_search").click(function () {
        init();
    });
});


function init() {
    $("#loading").show();
    if (r.flag_search) {
        allCourtCountTotalByYear();
    } else {
        courtCountTotalByYear();
    }
}

//var countNames = ['排期数', '开庭数', '准点数', '提前数', '滞后数', '异常数'];
var countNames = ['准点数', '提前数', '晚点数'];

/**
 * ajax 按照年 统计案件类型数据(柱状图)
 */
function courtCountTotalByYear() {
    var start = $("#startTime").find("input").val();
    var end = $("#endTime").find("input").val();
    $.ajax({
        url: r.base_path + "caseCount/getOnTimeCount",
        type: "post",
        data: {
            courtUid: r.court_uid,
            startDate: start,
            endDate: end,
            status: 0
        },
        dataType: "json",
        success: function (result) {
            result = result.data;
            $("#_content").show();
            $("#loading").hide();
            var openDeptTotals = [];
            var data = result[0];
//            openDeptTotals.push(data.planNum);
//            openDeptTotals.push(data.openNum);
            openDeptTotals.push(data.ontimeNum);
            openDeptTotals.push(data.advanceNum);
            openDeptTotals.push(data.latetimeNum);
//            openDeptTotals.push(data.exceptionNum);
            loadLeftCharts(openDeptTotals, countNames);
            loadDownChartsByCourtId(result);
        }
    });
}

function allCourtCountTotalByYear() {
    var start = $("#startTime").find("input").val();
    var end = $("#endTime").find("input").val();
    $.ajax({
        url: r.base_path + "caseCount/getOnTimeCount",
        type: "post",
        data: {
            courtUid: r.court_uid,
            startDate: start,
            endDate: end,
            status: 1
        },
        dataType: "json",
        success: function (result) {
            result = result.data;
            $("#_content").show();
            $("#loading").hide();
            result.sort(function compare(a, b) {
                return b.latetimeNum - a.latetimeNum;
            });
            resultValue = result;
            var courtNames = [];
            var ontimeNums = [];
            var advanceNums = [];
            var latetimeNums = [];
            $.each(result, function (i, ele) {
                courtNames[i] = ele.courtName;
                latetimeNums[i] = ele.latetimeNum;
                ontimeNums[i] = ele.ontimeNum;
                advanceNums[i] = ele.advanceNum;

            });
            allLoadLeftCharts(ontimeNums, advanceNums, latetimeNums, courtNames);
            allLoadDownChartsByCourtId(result);
        }
    });
}

function allLoadLeftCharts(ontimeNums, advanceNums, latetimeNums, list) {
    var myChart = echarts.init(document.getElementById('canvas'), "shine");
    var option = {
        title: {
            text: "开庭准点统计", //正标题
            x: "left", //标题水平方向位置
            textStyle: {
                fontSize: 24,
                color: "#FFFFFF"
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            textStyle: {
                color: "#FFFFFF"
            },
            show: true,
            data: ['准点次数', '提前次数', '晚点次数']
        },
        grid: {
            left: '6%',
            right: '3%'
            // bottom: '20%',
            // containLabel: true
        },
        xAxis: [
            {
                axisLabel: {
                    textStyle: {
                        fontSize: 16,
                        color: "#FFFFFF"
                    },
                    //rotate:-30,
                    interval: 0
                },
                type: 'category',
                data: list
            }
        ],
        yAxis: [
            {
                splitLine: {
                    show: false
                },
                splitArea: {
                    show: true,
                    areaStyle: {
                        color: ["#103d80", "#18498b"]
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: "#1c4e93"
                    }
                },
                axisLabel: {
                    textStyle: {
                        fontSize: 16,
                        color: "#FFFFFF"
                    }, formatter: function (value) {
                        return value;
                    }
                },
                type: 'value'
            }
        ],
        series: [
            {
                name: '准点次数',
                type: 'bar',
                data: ontimeNums,
                barMaxWidth: 20,
                itemStyle: {
                    normal: {
                        color: "#CEE02C",
                        label: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                color: "#CEE02C",
                                fontSize: 14
                            }
                        }
                    }
                }
            },
            {
                name: '提前次数',
                type: 'bar',
                barMaxWidth: 20,
                data: advanceNums,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                }
            },
            {
                name: '晚点次数',
                type: 'bar',
                barMaxWidth: 20,
                data: latetimeNums,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                }
            }
        ]
    };
    myChart.setOption(option);
    window.onresize = myChart.resize;
}

function loadLeftCharts(histogram, list) {
    var myChart = echarts.init(document.getElementById('canvas'), "shine");
    var option = {
        grid: { // 控制图的大小，调整下面这些值就可以，
            borderColor: "#1c4e93",
            x: '12%',
            y: "15%"
        },
        color: ["#d5b136"],
        tooltip: {
            show: true,
            formatter: "{b}<br/>{c}"
        },
        xAxis: {
            splitLine: {
                show: false
            },
            axisLabel: {
                textStyle: {
                    color: "#FFFFFF"
                },
                //rotate: -30,
                interval: 0,
                formatter: function (val) {
                    if (val.length == 4 || val.length == 5)
                        return val.substr(0, 2) + "\n" + val.substring(2);
                    else if (val.length == 6)
                        return val.substr(0, 3) + "\n" + val.substring(3);
                    else
                        return val;
                }
            },
            axisLine: {
                lineStyle: {
                    color: "#1c4e93"
                }
            },
            type: 'category',
            data: list
        }
        ,
        yAxis: {
            splitLine: {
                show: false
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ["#103d80", "#18498b"]
                }
            },
            axisLine: {
                lineStyle: {
                    color: "#1c4e93"
                }
            },
            axisLabel: {
                textStyle: {
                    color: "#FFFFFF"
                }, formatter: function (value) {
                    return value;
                }
            },
            type: 'value'
        }
        ,
        series: [
            {
                name: '',
                barWidth: 30,
                type: 'bar',
                data: histogram
            }
        ]
    };
    myChart.setOption(option);
    window.onresize = myChart.resize;
}

function loadDownChartsByCourtId(result) {
    $('#table').bootstrapTable({
        columns: [{
            field: 'Number',
            title: '序号',
            width: '5.3%',
            formatter: function (value, row, index) {
                return (index + 1) > 9 ? index + 1 : '0' + (index + 1);
            },
            footerFormatter: "总计"
        }, {
            field: 'ontimeNum',
            title: '准点数',
            class: '2',
            sortable: true,
            footerFormatter: function (result) {
                var total = 0;
                $(result).each(function (index, ele) {
                    total = total + ele.ontimeNum;
                });
                return total;
            }
        },
            {
                field: 'advanceNum',
                title: '提前数',
                class: '1',
                sortable: true,
                footerFormatter: function (result) {
                    var total = 0;
                    $(result).each(function (index, ele) {
                        total = total + ele.advanceNum;
                    });
                    return total;
                }
            },
            {
                field: 'latetimeNum',
                title: '晚点数',
                class: '3',
                sortable: true,
                footerFormatter: function (result) {
                    var total = 0;
                    $(result).each(function (index, ele) {
                        total = total + ele.latetimeNum;
                    });
                    return total;
                }
            }],
        data: result,
        showFooter: false
    });
    $('#table').bootstrapTable("load", result);
}
function allLoadDownChartsByCourtId(result) {
    $('#table').bootstrapTable({
        columns: [{
            field: 'Number',
            title: '序号',
            class: 'table-num',
            formatter: function (value, row, index) {
                return (index + 1) > 9 ? index + 1 : '0' + (index + 1);
            },
            footerFormatter: "总计"
        }, {
            field: 'courtName',
            title: '法院'
        }, {
            field: 'ontimeNum',
            title: '准点数',
            class: '2',
            sortable: true,
            footerFormatter: function (result) {
                var total = 0;
                $(result).each(function (index, ele) {
                    total = total + ele.ontimeNum;
                });
                return total;
            }
        },
            {
                field: 'advanceNum',
                title: '提前数',
                class: '1',
                sortable: true,
                footerFormatter: function (result) {
                    var total = 0;
                    $(result).each(function (index, ele) {
                        total = total + ele.advanceNum;
                    });
                    return total;
                }
            },
            {
                field: 'latetimeNum',
                class: '3',
                title: '晚点数',
                sortable: true,
                footerFormatter: function (result) {
                    var total = 0;
                    $(result).each(function (index, ele) {
                        total = total + ele.latetimeNum;
                    });
                    return total;
                }
            }, {
                field: 'courtUid',
                class: 'hidden',
                title: '法院id'
            }, {
                field: 'length',
                class: 'hidden',
                title: '子法院数'
            }],
        data: result,
        showFooter: true,
        onSort: function (name, order) {
            if ("latetimeNum" == name) {
                orderByLate(order);
            } else if ("advanceNum" == name) {
                orderByAdvance(order);
            } else if ("ontimeNum" == name) {
                orderByOnTime(order);
            }
        }
    });
    $('#table').bootstrapTable("load", result);

    //必须放在判断显示几列后面，否则不生效
    $('.fixed-table-footer').find('table').find('tbody').find('td').click(function () {
        var clickIndex = $(this).index();
        var clickType = $(this).attr('class');
        //获取当前的时间
        var start = $("#startTime").find("input").val();
        var end = $("#endTime").find("input").val();
        if (clickIndex > 1) {
            window.location.href = r.base_path + 'more/on_time_show?currentCourtUid=' + r.court_uid + '&onTimeType=' + clickType + '&courtUid=' + r.court_uid + '&start=' + start + '&end=' + end +  "&_search=true";
        }
    });

}

function orderByLate(order) {
    if ("asc" == order) {
        resultValue.sort(function compare(a, b) {
            return a.latetimeNum - b.latetimeNum;
        });
    } else {
        resultValue.sort(function compare(a, b) {
            return b.latetimeNum - a.latetimeNum;
        });
    }
    var courtnames = [];
    var ontimeNums = [];
    var advanceNums = [];
    var latetimeNums = [];
    $.each(resultValue, function (i, ele) {
        courtnames[i] = ele.courtname;
        latetimeNums[i] = ele.latetimeNum;
        ontimeNums[i] = ele.ontimeNum;
        advanceNums[i] = ele.advanceNum;

    });
    allLoadLeftCharts(ontimeNums, advanceNums, latetimeNums, courtnames);
}

function orderByAdvance(order) {
    if ("asc" == order) {
        resultValue.sort(function compare(a, b) {
            return a.advanceNum - b.advanceNum;
        });
    } else {
        resultValue.sort(function compare(a, b) {
            return b.advanceNum - a.advanceNum;
        });
    }
    var courtnames = [];
    var ontimeNums = [];
    var advanceNums = [];
    var latetimeNums = [];
    $.each(resultValue, function (i, ele) {
        courtnames[i] = ele.courtname;
        latetimeNums[i] = ele.latetimeNum;
        ontimeNums[i] = ele.ontimeNum;
        advanceNums[i] = ele.advanceNum;

    });
    allLoadLeftCharts(ontimeNums, advanceNums, latetimeNums, courtnames);
}

function orderByOnTime(order) {
    if ("asc" == order) {
        resultValue.sort(function compare(a, b) {
            return a.ontimeNum - b.ontimeNum;
        });
    } else {
        resultValue.sort(function compare(a, b) {
            return b.ontimeNum - a.ontimeNum;
        });
    }
    var courtnames = [];
    var ontimeNums = [];
    var advanceNums = [];
    var latetimeNums = [];
    $.each(resultValue, function (i, ele) {
        courtnames[i] = ele.courtname;
        latetimeNums[i] = ele.latetimeNum;
        ontimeNums[i] = ele.ontimeNum;
        advanceNums[i] = ele.advanceNum;

    });
    allLoadLeftCharts(ontimeNums, advanceNums, latetimeNums, courtnames);
}

function clickCell(cell) {
    var src = cell.srcElement || cell.target;
    src = $(src);
    //获取点击的列数
    var index = src.index();
    //获取点击的案件类型clickCaseType
    var type = $('#table').find('thead').find('tr:eq(0)').find("th:eq(" + index + ")").attr("class");
    //获取当前的时间
    var start = $("#startTime").find("input").val();
    var end = $("#endTime").find("input").val();

    if (r.flag_search) {
        //length为点击法院的子法院个数
        var length = src.parent().find("td:last").html();
        var lastIndex = src.parent().find("td:last").index();
        //clickCourtId为点击法院id
        var clickCourtId = src.parent().find("td:eq(" + (lastIndex - 1) + ")").html();
//		console.info(index,type,clickCaseType,length,clickCourtId);

        if (index == 1) {
            window.location.href = r.base_path + 'case_count/court_on_time_count?startTime=' + start + '&endTime=' + end + '&courtUid=' + clickCourtId;
        } else if (index > 1) {
            if (clickCourtId == r.court_uid) {

                window.location.href = r.base_path + 'more/on_time_show?currentCourtUid=' + clickCourtId + '&onTimeType=' + type + '&courtUid=' + r.court_uid + '&start=' + start + '&end=' + end + "&_search=false";
            } else {

                window.location.href = r.base_path + 'more/on_time_show?currentCourtUid=' + clickCourtId + '&onTimeType=' + type + '&courtUid=' + r.court_uid + '&start=' + start + '&end=' + end + "&_search=true";
            }
        }
    } else {
        //clickDeptId为点击的部门id
        var clickDeptId = src.parent().find("td:last").html();
//		console.info(index,type,clickDeptId);
        if (index > 0) {
            window.location.href = r.base_path + 'more/on_time_show?currentCourtUid=' + r.court_uid + '&onTimeType=' + type + '&courtUid=' + r.court_uid + '&start=' + start + '&end=' + end + "&_search=false";
        }

    }
}